Selection sort using ‘c’
Determination sort is another basic arranging calculation that over and over tracks down the base component from the unsorted piece of the cluster and trades it with the component toward the start of the unsorted part. This cycle is iteratively performed until the whole cluster is arranged.
Here is the bit by bit course of the choice sort calculation:
1. Set the principal component of the exhibit as the base worth.
2. Repeat through the unsorted piece of the cluster beginning from the subsequent component.
3. Contrast every component and the ongoing least worth.
4. In the event that a more modest component is found, update the base worth.
5. Subsequent to repeating through the unsorted part, trade the base worth with the principal component of the unsorted part.
6. Move the limit of the arranged section one situation to one side.
7. Rehash stages 2-6 until the whole cluster is arranged.
Program:-
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int n ;
printf("Enter the number of keys ");
scanf("%d",&n);
int arr[n];
printf("Enter the keys to be sort");
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Array before sorting: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nArray after sorting: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output
0 Comments